<template>
  <n-collapse accordion display-directive="show">
    <ContextMenu
      v-for="(item, index) of FriendGroupByUserMapCache"
      :key="index"
      :content="item"
      :menu-list="FriendListMenu"
      @select="(event, MenuItem) => MenuItem.click(event, item)"
    >
      <n-collapse-item :name="item.name" :title="item.name" class="px-1 py-2">
        <template #header-extra>
          <span class="text-[10px] text-fontPlaceholde px-2">
            {{ GroupOnlineRes(item.users || []) }}
          </span>
        </template>
        <div
          v-for="user in item.users"
          :class="activeItem === item.id ? 'bg-CenterHover' : ''"
          class="grid grid-cols-[40px_1fr] items-center hover:bg-CenterHover gap-1 p-2 rounded-sm"
          @click="SelectFriend(user)"
        >
          <n-avatar :src="user.avatar" />
          <div>
            <p class="text-base text-fontRegular font-medium">
              {{ user.name }}
            </p>
            <div class="flex flex-row text-xs text-fontPlaceholde">
              <div class="flex flex-row gap-1 items-center text-[10px]">
                [
                <UserStatus :status="user.status" />
                <span>{{ user.status === FriendStatus.online ? "在线" : "离线" }}</span>
                ]
              </div>
              <p>{{ user.sign }}</p>
            </div>
          </div>
        </div>
      </n-collapse-item>
    </ContextMenu>
  </n-collapse>
  <!--分组添加编辑弹窗-->
  <n-modal v-model:show="ShowModal.status">
    <div class="w-[350px] flex flex-col gap-3 p-4 bg-Center rounded">
      <p class="w-full flex flex-row justify-between items-center">
        <span class="text-fontRegular">{{ ShowModal.type != ShowFriendListModal.add ? "修改" : "添加" }}分组</span>
        <Close class="w-[16px] h-[16px] cursor-pointer text-fontPlaceholde" @click="ReSetModal" />
      </p>
      <n-input v-model:value="modalInputVal" :autofocus="false" :Placeholder="Placeholder" size="small"></n-input>
      <p class="text-end">
        <el-button size="small" @click="ReSetModal">取消</el-button>
        <el-button size="small" type="primary" @click="ModalConfirm">确认 </el-button>
      </p>
    </div>
  </n-modal>
</template>

<script lang="ts" setup>
import { computed, ref } from "vue";
import { storeToRefs } from "pinia";
import { FriendStatus, IFriendListItem, RightContentStatus, ShowFriendListModal } from "@/types/friend";
import { IUser } from "@/types/user";
import { CreateFriendGroup, UpdateFriendGroup } from "@/api/user.ts";
import { useCache } from "@/store/modules/cache.ts";
import { useFriendListMenu } from "@/hooks/useMenu.ts";
import ContextMenu from "@/components/ContextMenu/index.vue";
import UserStatus from "@/components/UserStatus/index.vue";
import { Close } from "@vicons/ionicons5";
import { NAvatar, NCollapse, NCollapseItem, NInput, NModal } from "naive-ui";

const cache = useCache();
const activeItem = ref(0);
let modalInputVal = ref("");
const { FriendGroupByUserMapCache } = storeToRefs(cache);
const { FriendListMenu, ShowModal, ReSetModal } = useFriendListMenu(modalInputVal);
const emit = defineEmits<{
  (e: "selectFriend", friendId: number, status: RightContentStatus): void;
}>();

const GroupOnlineRes = computed(() => (us: IUser[]): string => {
  const online = us.filter((u) => u.status === FriendStatus.online).length;
  return `${online}/${us.length}`;
});

const Placeholder = computed(() => {
  if (ShowModal.value.type != ShowFriendListModal.add) {
    return "请输入修改分组名";
  } else {
    return "请输入添加分组名";
  }
});

// 点击选择
function SelectFriend(user: IFriendListItem) {
  activeItem.value = user.id;
  emit("selectFriend", user.id, RightContentStatus.friendDetail);
}

// 弹窗确认
async function ModalConfirm() {
  if (modalInputVal.value == "") return;
  try {
    if (ShowModal.value.type === ShowFriendListModal.add) {
      let res = await CreateFriendGroup(modalInputVal.value);
      if (!res || res.status != 200) throw Error("添加失败");
      cache.AddFriendGroupMapCache(res.data);
    } else {
      let data = {
        id: ShowModal.value.friendGroupId!,
        name: modalInputVal.value,
      };
      let res = await UpdateFriendGroup(data);
      if (!res || res.status != 200) throw Error("修改失败");
      cache.UpdateFriendGroupCacheByName(data);
    }
  } catch (error) {
    console.error("分组请求失败:", error);
  } finally {
    ReSetModal();
  }
}
</script>

<style lang="scss" scoped></style>
